var listingWidgetCurrentPage                    = 0;
var listingWidgetLastPage                       = -1;

var listingWidgetMapList                        = new Array();
var listingWidgetListList                       = new Array();

var listingWidgetCurrentBuildingOrUnit          = null;
var listingWidgetCurrentBuilding                = null;
var listingWidgetBuildingIndex                  = 0;
var listingWidgetUnitIndex                      = 0;
var listingWidgetDetailImageIndex               = 0;

var listingWidgetUnitMode                       = false;

var listingWidgetDetailMap                      = null;

if (typeof listingWidgetForSaleMode == undefined) {
    var listingWidgetForSaleMode      = false;
}

if (typeof listingWidgetDefaultMapVisible == undefined) {
    var listingWidgetDefaultMapVisible      = true;
}

if (typeof listingWidgetStaticMode == undefined) {
    var listingWidgetStaticMode      = false;
}


/**
 * Initialize using jQuery
 */
jQuery(function() {
    jQuery("#pw_listing_widget_tabs").tabs( {
        select: function (event, ui) {
            loadTab(ui.panel.id);
            jQuery("#pw_listing_widget_searchFormSelectedTab").attr("value", ui.panel.id);
        }
    });

    jQuery("#pw_listing_widget_tabs_detail_inner_tabs").tabs( {
        select: function (event, ui) {
            if (ui.panel.id == 'tabs-2') {
                loadListingDetailMap();
            }
        }
    });

   jQuery("body").append( jQuery("#pw_listing_widget_image_popup"));

    jQuery("input.date").datepicker();

    loadSearchParams();
    setupSearchFormEventHandlers();
    setupNotifyMeForm();
    loadSelectedTab();

});

function loadSelectedTab() {
    var uid = getParam("uid");
    var bid = getParam("bid");
    var selectedTab = getParam("selectedTab");
    if (uid != null || bid != null) {
        jQuery("#pw_listing_widget_tabs").tabs('select', "pw_listing_widget_tabs_detail");
    } else if (selectedTab == 'pw_listing_widget_tabs_list') {
        jQuery("#pw_listing_widget_tabs").tabs('select', selectedTab);
    } else if (!listingWidgetDefaultMapVisible) {
        jQuery("#pw_listing_widget_tabs").tabs('select', "pw_listing_widget_tabs_list");
     } else {
        loadTab("pw_listing_widget_tabs_map");
    }
}

/**
 * Loads a tab with a given id
 * @param tabID
 */
function loadTab(tabID) {
    switch (tabID) {
        case 'pw_listing_widget_tabs_list':
            loadList();
            break;
        case 'pw_listing_widget_tabs_detail':
            loadDetail();
            break;
        default:
            loadMap();
            break;
    }
}

/**
 * Loads parameters for the search page
 */
function loadSearchParams() {
    jsonRequest(RENTAL_SEARCH_WIDGET_BASE_URL+"&action=s"+ "&forSale="+listingWidgetForSaleMode, 'loadSearchParamsCallback');
}

function loadSearchParamsCallback(jsonObj) {
    var unitTypesArray = listingWidgetForSaleMode?jsonObj.forSaleUnitTypes:jsonObj.unitTypes;
    var amenitiesArray = jsonObj.amenities;
    var leasingContactsArray = jsonObj.leasingContacts;

    var unitTypesHtml =  "<option value=''>All</option>\n";
    for(var i = 0; i < unitTypesArray.length; i++) {
        unitTypesHtml += "<option value=\"" + unitTypesArray[i]  + "\">" + unitTypesArray[i] + "</option>\n";
    }
    jQuery("#typeField").html(unitTypesHtml);

    var amenitiesHtml = "";
    for(i = 0;  i < amenitiesArray.length; i++){
        amenitiesHtml += "<li class=\"amenitiesListItem\"><input type=\"checkbox\" name='amnts' value=\""+amenitiesArray[i][0]+"\"> "+ amenitiesArray[i][0] + "</li>";
    }
    jQuery("#pw_listing_widget_search_amenities_list").html(amenitiesHtml);

    if (jsonObj.showAgentFilter) {
        var leasingContactsHtml = "";
        for(i = 0;  i < leasingContactsArray.length; i++){
            leasingContactsHtml += "<li class=\"leasingContactsListItem\"><input type=\"checkbox\" name='lsgCont' value=\""+leasingContactsArray[i].id+"\"> "+ leasingContactsArray[i].name + "</li>";
        }
        jQuery("#pw_listing_widget_search_leasing_contacts_list").html(leasingContactsHtml);
    } else {
        jQuery("#pw_listing_widget_search_leasing_contacts_div").hide();
    }

    // populate form from request params
    jQuery("#addrField").attr("value", getParam("addr")!=null?getParam("addr"):"");
    jQuery("#minField").attr("value", getParam("min")!=null?getParam("min"):"");
    jQuery("#maxField").attr("value", getParam("max")!=null?getParam("max"):"");
    jQuery("#typeField").find("option[value ='"+getParam("type")+"']").attr("selected", "true");
    jQuery("#bedsField").find("option[value ='"+getParam("beds")+"']").attr("selected", "true");
    jQuery("#bathsField").find("option[value ='"+getParam("baths")+"']").attr("selected", "true");
    jQuery("#sortSelect").find("option[value ='"+getParam("sort")+"']").attr("selected", "true");
    jQuery("#sortField").attr("value", getParam("sort"));

    // populate checked amenities
    var checkedAmenities = getParam("amnts");
    if (jQuery.isArray(checkedAmenities)) {
        for (var k = 0; k <  checkedAmenities.length; k++) {
            jQuery("#pw_listing_widget_search_amenities_list input[value = '"+checkedAmenities[k]+"']").attr("checked", "true");
        }
    } else {
        jQuery("#pw_listing_widget_search_amenities_list input[value = '"+checkedAmenities+"']").attr("checked", "true");
    }

    // populate checked contacts
    var checkedContacts = getParam("lsgCont");
    if (jQuery.isArray(checkedContacts)) {
        for (var j = 0; j <  checkedContacts.length; j++) {
            jQuery("#pw_listing_widget_search_leasing_contacts_list input[value = '"+checkedContacts[j]+"']").attr("checked", "true");
        }
    } else {
        jQuery("#pw_listing_widget_search_leasing_contacts_list input[value = '"+checkedContacts+"']").attr("checked", "true");
    }


    // populate contact us form
    var cityList = jsonObj.cityList;
    var cityListSelect = jQuery("#webform_guest_cityDesired");
    for(i = 0;  i < cityList.length; i++){
        cityListSelect.append("<option value='"+cityList[i]+"'>"+cityList[i]+"</option>");
    }
    var typList = listingWidgetForSaleMode?jsonObj.forSaleUnitTypes:jsonObj.unitTypes;
    var typListSelect = jQuery("#webform_guest_unitTypeDesired");
    for(i = 0;  i < typList.length; i++){
        typListSelect.append("<option value='"+typList[i]+"'>"+typList[i]+"</option>");
    }
}

function setupSearchFormEventHandlers() {
    //jQuery("#pSeachButton").click(searchPublishedRentals);
    jQuery("#moreSearchOptsSpan").click(function(){
        var row = jQuery("#moreOptsRow");
        if(row.is(":hidden")){
            row.show();
        } else {
            row.hide();
        }
    });

    jQuery("#sortSelect").change(function() {
        jQuery("#sortField").attr("value", jQuery(this).attr("value"));
        jQuery("#pw_listing_widget_searchForm").submit();
    });
}

function setupNotifyMeForm() {
    jQuery("#pw_listing_widget_wait_list_dialog").dialog({width: "640px", show: 'slide', autoOpen:false, modal:true});
    jQuery("#pw_listing_widget_wait_list_dialog_confirmation").dialog({width: "480px", show: 'slide', autoOpen:false, modal:true,
        buttons: {
            Ok: function() {
                jQuery(this).dialog('close');
            }
        }});
    jQuery("#submitTenantWaitListForm").click(submitTenantWaitListForm);
    jQuery("#cancelTenantWaitListForm").click(cancelTenantWaitListForm);
}


function setupDirectionsForm(jsonObject) {
    jQuery("#pw_listing_widget_tabs_detail_directions_dialog").dialog({width: "380px", show: 'slide', autoOpen:false, modal:true});

    jQuery("#pw_listing_widget_tabs_detail_directionsForm_Go").click(function() {
        if (jsonObject.unit != null && (jsonObject.hideAddress == undefined || jsonObject.hideAddress == null || !jsonObject.hideAddress)) {
            var fromAddr = document.getElementById("pw_listing_widget_tabs_detail_directions_dialog_fromAddress").value;
            var toAddr = jsonObject.unit.address +","+jsonObject.unit.city +","+jsonObject.unit.state;

            fromAddr = fromAddr.replace(/ /g,"+");
            toAddr = toAddr.replace(/ /g,"+");

            var googleUrl = "http://maps.google.com/maps?saddr="+fromAddr+"&daddr="+toAddr;
            window.open (googleUrl,"Directions");
            jQuery("#pw_listing_widget_tabs_detail_directions_dialog").dialog('close');
        }
    });
    jQuery("#pw_listing_widget_tabs_detail_directionsForm_Cancel").click(function() {
        jQuery("#pw_listing_widget_tabs_detail_directions_dialog").dialog('close');
    });
}

/**
 * Loads the map with a JSON request
 */
function loadMap() {
    try {
        var url = RENTAL_SEARCH_WIDGET_BASE_URL+"&action=qml"+ "&forSale="+listingWidgetForSaleMode;
        if(self.location.search.substring(1) != "") {
            url += "&" + self.location.search.substring(1);
        }
        jsonRequest(url, 'loadMapCallback');
    } catch (e) {
        jQuery("#pw_listing_widget_tabs_main_map").html("There was a problem loading the map. Please try again later.");
    }
}

/**
 * Callback function for loading the map
 * @param jsonObject
 */
function loadMapCallback(jsonObject) {
    // check if listingWidgetMapList has already been loaded for this page
    if (listingWidgetMapList !== null && listingWidgetMapList.length > 0) {
        //GEvent.trigger(listingWidgetMapList[listingWidgetBuildingIndex].marker, "click");
        return;
    }

    var map = new GMap2(document.getElementById("pw_listing_widget_tabs_main_map"));
    map.setCenter(new GLatLng( 0,0), 9);
    map.setUIToDefault();

    var bounds = new GLatLngBounds();

    var preImage = new Image();
    preImage.src = "../www.propertyware.com/pw/website/widgets/images/flag.png";

    var preShadow = new Image();
    preShadow.src = "../labs.google.com/ridefinder/images/mm_20_shadow.png";

    var preTransparent = new Image();
    preTransparent.src = "../maps.google.com/mapfiles/transparent.png";

    var tiny = new GIcon();
    tiny.image = preImage.src;
    tiny.shadow = preShadow.src;
    tiny.iconSize = new GSize(12, 20);
    tiny.shadowSize = new GSize(22, 20);
    tiny.iconAnchor = new GPoint(6, 20);
    tiny.infoWindowAnchor = new GPoint(5, 1);
    tiny.imageMap = [4,0,0,4,0,7,3,11,4,19,7,19,8,11,11,7,11,4,7,0];
    tiny.transparent = preTransparent.src;

    var buildings = jsonObject.buildings;
    var buildingCount = buildings.length;
    if( buildingCount > 0){
        for (var i=0; i < buildingCount; i++) {
            var lat = parseFloat(buildings[i].latitude);
            var lng = parseFloat(buildings[i].longitude);
            var point = new GLatLng(lat,lng);

            point.textArray = buildings[i];
            var label = point.textArray[2];
            if(point!='(0, 0)'){
                point.marker = new GMarker(point,{title: label, icon:tiny});
                point.marker.building = buildings[i];
                point.marker.buildingID = buildings[i].id;
                point.marker.buildingIndex = i;
                GEvent.addListener(point.marker, "infowindowopen", function() {
                    loadInfoWindow(this);
                });
                map.addOverlay(point.marker);
                bounds.extend(point);
                point.marker.bindInfoWindow(createInfoWindow( buildings[i].id));
                /**
                 *  put the marker on the building to use later when coming from the list to the map
                 */
                buildings[i].marker = point.marker;
            }
        }
    }
    var opts = {top:0, right:0, bottom:0, left:0, save: true, disableSetCenter: false};
    var ty = map.getCurrentMapType();
    var port = map.getSize();
    if(!opts.disableSetCenter){
        var virtualPort = new GSize(port.width - opts.left - opts.right,
                port.height - opts.top - opts.bottom);
        map.setZoom(ty.getBoundsZoomLevel(bounds, virtualPort));
        var xOffs = (opts.left - opts.right)/2;
        var yOffs = (opts.top - opts.bottom)/2;
        var bPxCenter = map.fromLatLngToDivPixel(bounds.getCenter());
        var newCenter = map.fromDivPixelToLatLng(new GPoint(bPxCenter.x-xOffs, bPxCenter.y-yOffs));
        map.setCenter(newCenter);
        if(opts.save)map.savePosition();
    }

    /**
     * Important! set the new list of buidings for the  listingWidgetMapList
     *
     * this is needed for the detail view
     */
    listingWidgetMapList = buildings;

    jQuery("#pw_listing_widget_tabs_map_number_listings").html(jsonObject.unitCount);
}

function createInfoWindow(buildingID) {
    var contentDiv = jQuery(".pw_listing_widget_tabs_map_info_window_template").clone();
    contentDiv.attr("id", "info_window_content_"+buildingID);
    contentDiv.attr("init", "false");
    contentDiv.show(); // doing this here makes it work for all 3 browsers including stupid IE
    return contentDiv.get(0);
}

function loadInfoWindow(marker) {
    if (jQuery("#info_window_content_"+marker.buildingID).attr("init") == "false") {
        jsonRequest(RENTAL_SEARCH_WIDGET_BASE_URL+"&bid="+marker.buildingID+ "&buildingIndex="+marker.buildingIndex+"&action=b"+ "&forSale="+listingWidgetForSaleMode, 'loadInfoWindowCallback');
    }
}

function loadInfoWindowCallback(jsonObject) {
    // clone template div and append it to info window
    var contentDiv = jQuery("#info_window_content_"+jsonObject.building.id);
    contentDiv.attr("init", "true");
    contentDiv.show(); // doing this here makes it work for all 3 browsers including stupid IE

   // populate info
    var address = jsonObject.building.address;
    if(address.length > 24){
        address = address.substring(0,24);
        address = address + "...";
    }
    var cityState = jsonObject.building.city + ",  " + jsonObject.building.state;
    if(cityState.length > 24){
        cityState = cityState.substring(0,24);
        cityState = cityState + "..."; 
    }
    if (jsonObject.hideAddress == undefined || jsonObject.hideAddress == null || !jsonObject.hideAddress) {
        contentDiv.find(".infoWindowAddrSpan").html("<a href='javascript:gotoDetail("+jsonObject.buildingIndex+")'>" + address + "</a>");
    } else {
        contentDiv.find(".infoWindowAddrSpan").html("<a href='javascript:gotoDetail("+jsonObject.buildingIndex+")'>" + View + "</a>");
    }
    contentDiv.find(".infoWindowCityStateZipSpan").html(cityState);
    contentDiv.find(".infoWindowPriceSpan").html(listingWidgetForSaleMode?jsonObject.building.salePrice:jsonObject.building.startingRent);
    contentDiv.find(".infoWindowTypeSpan").html(jsonObject.building.type);
    if (jsonObject.building.rentable == 'true') {
        contentDiv.find(".infoWindowDescSpan").html(jsonObject.building.numberBedrooms +" Bed | "+jsonObject.building.numberBathrooms+" Bath | "+jsonObject.building.totalArea   + " "+jsonObject.building.areaUnits);
    }
    contentDiv.find(".infoWindowMoreDetails").html("<a href='javascript:gotoDetail("+jsonObject.buildingIndex+")'>More Details</a>" );
    if (jsonObject.building.images.length > 0 != null) {
        var buildingImage = jsonObject.building.images[0];
        contentDiv.find(".infoWindowImg").attr("src", buildingImage.url);
    }

}

function loadList() {
    if (listingWidgetStaticMode && document.location.href.indexOf("?") < 0) {
        listingWidgetStaticMode =false;
        return;
    }
    // check if list has already been loaded for this page
    if (listingWidgetCurrentPage == listingWidgetLastPage) {
        return;
    }
    if(self.location.search.substring(1) != "") {
        jsonRequest(RENTAL_SEARCH_WIDGET_BASE_URL+"&forSale="+listingWidgetForSaleMode+"&action=l&"+self.location.search.substring(1)+"&pageNumber=" +listingWidgetCurrentPage, 'loadListCallback');
    } else {
        jsonRequest(RENTAL_SEARCH_WIDGET_BASE_URL+"&forSale="+listingWidgetForSaleMode+"&action=l"+"&pageNumber=" +listingWidgetCurrentPage, 'loadListCallback');
    }
}

function loadListCallback(jsonObject) {
    var buildings = jsonObject.buildings;
    var buildingCount = buildings.length;
    var startingCount = jsonObject.pageSize * listingWidgetCurrentPage ;
    var showingCount = startingCount + buildingCount;
    var totalCount = jsonObject.unitCount;
    if(buildingCount > 0) {
        var liTemplate = jQuery(".pw_listing_widget_tabs_list_item_template");
        var ul = jQuery("#pw_listing_widget_tabs_list_ul");
        for (var i = 0; i < buildingCount; i++) {
            var currentIndex = startingCount + i;
            var li;
            //alert(li.id);
            if (document.getElementById("pw_listing_widget_tabs_list_item_"+i) == undefined) {
                li = liTemplate.clone();
                li.attr("id", "pw_listing_widget_tabs_list_item_"+buildings[i].id);
                ul.append(li);
            } else {
                li = jQuery("#pw_listing_widget_tabs_list_item_"+i);

            }
            li.attr("class", "pw_listing_widget_tabs_list_item");
            li.attr("style", "display: block");

            var address = "";
            if (jsonObject.hideAddress == undefined || jsonObject.hideAddress == null || !jsonObject.hideAddress) {
                address =  buildings[i].address + ", " + buildings[i].city + ",  " + buildings[i].state + " " + buildings[i].zip;
            }
            // populate info -todo use less javascript for this
            var html = "<a href='javascript:gotoDetail("+currentIndex+")'>" + buildings[i].postingTitle + "</a><br/>" + address  ;
            html += "<br />";
            html += "<br />";
            html += "<table style='width: 100%'>";
            html += "<tr >";
            html += "<td style='width: 35%;vertical-align: top;'>";
            html +=      " <span class=\"boldFont\">Type: </span>"+buildings[i].type +"";
            html += "</td>";
            html += "<td style='width: 48%;vertical-align: top;'>";
            html +=      listingWidgetForSaleMode?"<span class=\"boldFont\">Sale Price: </span> "+buildings[i].salePrice+"<br /><span class=\"boldFont\">"+buildings[i].forSaleStatus +"</span>": getRent(buildings[i]);
            html += "</td>";
            html += "<td style='width: 7.5%;vertical-align: top;'>";
            if (buildings[i].rentable) {
                html +=      " <span class=\"boldFont\">BR: </span>"+buildings[i].numberOfBedrooms +"";
            }
            html += "</td>";
            html += "<td style='width: 9.5%;vertical-align: top;'>";
            if (buildings[i].rentable) {
                html +=      " <span class=\"boldFont\">BA: </span>"+buildings[i].numberOfBathrooms +"";
            }
            html += "</td>";

            html += "</tr>";
            html += "</table>";
            html += "<br />";
            html += "<p>"+buildings[i].commentsAbbreviated+"</p>";
            html += "<br />";
            li.find(".listItemDescTd").html(html);
            li.find(".listItemImgTd a.listItemImgTdMapLink").attr("href", "javascript:showOnMap("+currentIndex+")");
            li.find(".listItemImgTd a.listItemImgTdUnitLink").attr("href", "javascript:gotoDetail("+currentIndex+")");

            var img = li.find("img.pw_listing_widget_tabs_list_item_img");
            var buildingImages = buildings[i].images;
            var buildingImagesCount = buildingImages.length;
            if (buildingImagesCount > 0) {
                img.attr("src", buildingImages[0].url);
            } else {
                img.attr("src", "../www.propertyware.com/pw/website/widgets/images/pw_listing_widget_no_photo.png");
            }

            if (!buildings[i].rentable) {
                li.find(".showWhenMultiBuilding").show();
            } else {
                li.find(".showWhenMultiBuilding").hide();
            }

            /**
             * Important! set the new list of buidings for the  listingWidgetMapList
             *
             * this is needed for the detail view
             */
            listingWidgetListList[currentIndex] = buildings[i];

        }

        if (totalCount > showingCount ) {
            ul.append("<li class='pw_listing_widget_tabs_list_item pw_listing_widget_tabs_list_item_load_more_li'> <a class='pw_listing_widget_tabs_list_item_load_more_link' href='javascript:loadNextPage()'>Showing "+showingCount+" out of "+totalCount+". Show More ...</a> </li>");
        } else {
            ul.append("<li class='pw_listing_widget_tabs_list_item pw_listing_widget_tabs_list_item_load_more_li'> <span class='pw_listing_widget_tabs_list_item_load_more_link'>Showing "+showingCount+" out of "+totalCount+"</span> </li>");
        }
        listingWidgetLastPage = listingWidgetCurrentPage;
    }
    jQuery("#pw_listing_widget_tabs_list_number_listings").html(jsonObject.unitCount);

}

function getRent(building){

    return building.targetRent;
//    return "<span class=\"boldFont\">"+ "rent"+" : </span>"+building.startingRent+"";
}
function loadNextPage() {
    listingWidgetCurrentPage++;
    jQuery(".pw_listing_widget_tabs_list_item_load_more_li").remove();
    loadList();
}


function loadDetail() {
    jQuery("#pw_listing_widget_tabs_detail_container").fadeOut();
    var uid = getParam("uid");
    var bid = getParam("bid");
    if (listingWidgetBuildingIndex >= 0 && listingWidgetMapList[listingWidgetBuildingIndex] != null) {
        var building = listingWidgetMapList[listingWidgetBuildingIndex];
        if (listingWidgetUnitMode && building.publishedUnits != null && building.publishedUnits[listingWidgetUnitIndex]) {
            var unit = building.publishedUnits[listingWidgetUnitIndex];
            uid = unit.id;
        } else {
            uid = building.id;
            listingWidgetUnitMode = false;
        }
        jsonRequest(RENTAL_SEARCH_WIDGET_BASE_URL+"&uid="+uid+"&action=u"+ "&sid="+SID+ "&forSale="+listingWidgetForSaleMode, 'loadDetailCallback');
    } else if (listingWidgetBuildingIndex >= 0 && listingWidgetListList[listingWidgetBuildingIndex] != null) {
        var building2 = listingWidgetListList[listingWidgetBuildingIndex];
        if (listingWidgetUnitMode && building2.publishedUnits != null && building2.publishedUnits[listingWidgetUnitIndex]) {
            var unit2 = building2.publishedUnits[listingWidgetUnitIndex];
            uid = unit2.id;
        } else {
            uid = building2.id;
            listingWidgetUnitMode = false;
        }
        jsonRequest(RENTAL_SEARCH_WIDGET_BASE_URL+"&uid="+uid+"&action=u"+ "&sid="+SID+ "&forSale="+listingWidgetForSaleMode, 'loadDetailCallback');
    } else if (uid != null) {
        jsonRequest(RENTAL_SEARCH_WIDGET_BASE_URL+"&uid="+uid+"&action=u"+ "&sid="+SID+ "&forSale="+listingWidgetForSaleMode, 'loadDetailCallback');
    } else if (bid != null) {
        jsonRequest(RENTAL_SEARCH_WIDGET_BASE_URL+"&uid="+bid+"&action=u"+ "&sid="+SID+ "&forSale="+listingWidgetForSaleMode, 'loadDetailCallback');
    } else {
        jQuery("#pw_listing_widget_tabs").tabs('select', 'pw_listing_widget_tabs_map');
    }
}

function loadUnitDetail(unitIndex) {
    listingWidgetUnitMode = true;
    listingWidgetUnitIndex = unitIndex;
    var publishedUnits = listingWidgetForSaleMode?listingWidgetCurrentBuilding.publishedUnitsForSale:listingWidgetCurrentBuilding.publishedUnits;
    uid = publishedUnits[listingWidgetUnitIndex].id;
    jsonRequest(RENTAL_SEARCH_WIDGET_BASE_URL+"&uid="+uid+"&action=u"+ "&sid="+SID+ "&forSale="+listingWidgetForSaleMode, 'loadDetailCallback');
}

function loadDetailCallback(jsonObject) {
    var unit = jsonObject.unit;
    if (unit != null) {
        listingWidgetCurrentBuildingOrUnit = unit;

        if (listingWidgetUnitMode) {
            jQuery("#pw_listing_widget_tabs_detail_back_to_building").show('slide');
        } else {
            jQuery("#pw_listing_widget_tabs_detail_back_to_building").hide();
        }

        setupDirectionsForm(jsonObject);

        var address = "";
        if (jsonObject.hideAddress == undefined || jsonObject.hideAddress == null || !jsonObject.hideAddress) {
            address =  unit.address + ", "  + unit.city + ", " + unit.state + " " + unit.zip;
        }
        jQuery("#pw_listing_widget_tabs_detail_posting_title").html(unit.postingTitle);
        jQuery("#pw_listing_widget_tabs_detail_address").html(address);
        jQuery("#pw_listing_widget_tabs_detail_deposit").html(unit.targetDeposit);
        jQuery("#pw_listing_widget_tabs_detail_available").html(unit.availableDateDesc);
        jQuery("#pw_listing_widget_tabs_detail_min_lease").html(unit.leaseTerms + ' ' + unit.leaseTermsUnits);
        jQuery("#pw_listing_widget_tabs_detail_type").html(unit.type);
        jQuery("#pw_listing_widget_tabs_detail_area").html(unit.totalArea);
        jQuery("#pw_listing_widget_tabs_detail_bed").html(unit.numberBedrooms);
        jQuery("#pw_listing_widget_tabs_detail_bath").html(unit.numberBathrooms);
        jQuery("#pw_listing_widget_tabs_detail_mls").html(unit.mlsNumber);
        jQuery("#pw_listing_widget_tabs_detail_sale_terms").html(unit.saleTerms);
        jQuery("#pw_listing_widget_tabs_detail_sale_status").html(unit.forSaleStatus);
        jQuery("#pw_listing_widget_tabs_detail").show();
        if (listingWidgetForSaleMode) {
            jQuery("#pw_listing_widget_tabs_detail_price").html(unit.salePrice);
            jQuery("#pw_listing_widget_tabs_detail_year_built").html(unit.building.yearBuilt);
        } else {
            if (unit.rentable) {
                jQuery("#pw_listing_widget_tabs_detail_price").html(unit.targetRentDescription);
            } else {
                jQuery("#pw_listing_widget_tabs_detail_price").html("From "+unit.startingRentAmount);
            }
        }
        if (unit.comments == null || unit.comments == '') {
            jQuery("#pw_listing_widget_tabs_detail_description").hide();
        } else {
            jQuery("#pw_listing_widget_tabs_detail_description_p").html(unit.comments);
            jQuery("#pw_listing_widget_tabs_detail_description").show();
        }

        if (unit.otherTenantCharges == null || unit.otherTenantCharges == '') {
            jQuery("#pw_listing_widget_tabs_detail_other_tenant_charges").hide();
        } else {
            jQuery("#pw_listing_widget_tabs_detail_other_tenant_charges_p").html(unit.otherTenantCharges);
            jQuery("#pw_listing_widget_tabs_detail_other_tenant_charges").show();
        }

        jQuery("#pw_listing_widget_tabs_detail_detailApplyOnlineLink").attr("href",TENANT_APPLICATION_URL+"?unitID="+unit.id);


        // images
        listingWidgetDetailImageIndex = 0;
        var unitImages = unit.images;
        var unitImageCount = unitImages.length;
        if(unitImageCount >= 1) {

            jQuery("#pw_listing_widget_tabs_detail_image").attr("src",unitImages[0]);
            jQuery("#pw_listing_widget_tabs_detail_imageControls").show();
            jQuery("#pw_listing_widget_tabs_detail_image").attr("src",unitImages[listingWidgetDetailImageIndex].url);

            jQuery("#pw_listing_widget_tabs_detail_image").unbind("click").click(function() {
                jQuery("#pw_listing_widget_tabs_detail_detailImageCounter").click();
            });

            jQuery("#pw_listing_widget_tabs_detail_detailImageCounter").unbind("click").click(function() {
                if(jQuery("#popupMask").length == 0){
                    jQuery('<div id=\"popupMask\"></div>').appendTo('body');
                }
                jQuery('#popupMask').width("100%");
                jQuery('#popupMask').height(jQuery(document).height());

                jQuery('#popupImg').attr("src",unitImages[listingWidgetDetailImageIndex].highResUrl);
                jQuery('#popupImgCaption').html(unitImages[listingWidgetDetailImageIndex].description);
                jQuery('#popupImg').load(function(){
                    var imgHeight = getNaturalHeight(this);
                    var imgWidth = getNaturalWidth(this);
                    if (imgHeight > 600) {
                        imgWidth *= 600/imgHeight;
                        imgHeight = 600;
                    }
                    if (imgWidth > 800) {
                        imgHeight *= 800/imgWidth;
                        imgWidth = 800;
                    }
                    jQuery('#popupImg').css({width: imgWidth, height:imgHeight});
                    windowCentered("pw_listing_widget_image_popup");
                    jQuery('#pw_listing_widget_image_popup').fadeIn();
                });

                jQuery('#imageClose').unbind("click").click(function(){
                    jQuery('#popupMask').hide();
                    jQuery('#pw_listing_widget_image_popup').hide();
                });
                if (unitImageCount > 1) {
                    jQuery("#zoomLeft").unbind("#click").click(function(){
                        jQuery("#pw_listing_widget_tabs_detail_detailImageLeft").click();
                        jQuery('#popupImg').attr("src",unitImages[listingWidgetDetailImageIndex].highResUrl);
                        jQuery('#popupImgCaption').html(unitImages[listingWidgetDetailImageIndex].description);
                    });
                    jQuery("#zoomRight").unbind("#click").click(function(){
                        jQuery("#pw_listing_widget_tabs_detail_detailImageRight").click();
                        jQuery('#popupImg').attr("src",unitImages[listingWidgetDetailImageIndex].highResUrl);
                        jQuery('#popupImgCaption').html(unitImages[listingWidgetDetailImageIndex].description);
                    });
                } else {
                    jQuery("#zoomLeft").hide();
                    jQuery("#zoomRight").hide();
                }

                var imgHeight = getNaturalHeight(this);
                var imgWidth = getNaturalWidth(this);
                jQuery('#imageClose').css("top",((jQuery(window).height() - imgHeight)/2)+document.body.scrollTop-34);
                jQuery('#imageClose').css("left",((jQuery('body').width() - imgWidth)/2)+(imgWidth +3)-6);
                jQuery('#popupImgDiv').css("top",((jQuery(window).height() - imgHeight)/2)+document.body.scrollTop);
                jQuery('#popupImgDiv').css("left",((jQuery('body').width() - imgWidth)/2));
                jQuery('#zoomImgControls').css("top",((jQuery(window).height() + imgHeight)/2)+document.body.scrollTop+10);
                jQuery('#zoomImgControls').css("left",((jQuery('body').width() - 90)/2));
                //--
                jQuery('#popupMask').show();

            });

            if (unitImageCount > 1) {
                jQuery("#pw_listing_widget_tabs_detail_detailImageLeft").show();
                jQuery("#pw_listing_widget_tabs_detail_detailImageRight").show();
                jQuery("#pw_listing_widget_tabs_detail_detailImageLeft").unbind("click").click(function(){
                    if(listingWidgetDetailImageIndex == 0){
                        listingWidgetDetailImageIndex = unitImages.length - 1;
                        iId = unitImages[listingWidgetDetailImageIndex].smallID;
                        jQuery("#pw_listing_widget_tabs_detail_image").attr("src",unitImages[listingWidgetDetailImageIndex].url);
                    }else{
                        listingWidgetDetailImageIndex--;
                        iId = unitImages[listingWidgetDetailImageIndex].smallID;
                        jQuery("#pw_listing_widget_tabs_detail_image").attr("src",unitImages[listingWidgetDetailImageIndex].url);
                    }
                    //jQuery("#detailImageCounter").html((listingWidgetDetailImageIndex+1)+" of "+unitImages.length);
                });
                //jQuery("#detailImageCounter").html((listingWidgetDetailImageIndex+1)+" of "+unitImages.length);
                jQuery("#pw_listing_widget_tabs_detail_detailImageRight").unbind("click").click(function(){
                    if(listingWidgetDetailImageIndex == (unitImages.length - 1)){
                        listingWidgetDetailImageIndex = 0;
                        iId = unitImages[listingWidgetDetailImageIndex].smallID;
                        jQuery("#pw_listing_widget_tabs_detail_image").attr("src",unitImages[listingWidgetDetailImageIndex].url);
                    }else{
                        listingWidgetDetailImageIndex++;
                        iId = unitImages[listingWidgetDetailImageIndex].smallID;
                        jQuery("#pw_listing_widget_tabs_detail_image").attr("src",unitImages[listingWidgetDetailImageIndex].url);
                    }
                    //jQuery("#detailImageCounter").html((listingWidgetDetailImageIndex+1)+" of "+unitImages.length);
                });
            } else {
                jQuery("#pw_listing_widget_tabs_detail_detailImageRight").hide();
                jQuery("#pw_listing_widget_tabs_detail_detailImageLeft").hide();
            }

        }
        else{
            jQuery("#pw_listing_widget_tabs_detail_imageControls").hide();
            jQuery("#pw_listing_widget_tabs_detail_image").attr("src","../www.propertyware.com/pw/website/widgets/images/pw_listing_widget_no_photo.png");
        }

        // units
        var publishedUnits = listingWidgetForSaleMode?unit.publishedUnitsForSale:unit.publishedUnits;
        var publishedUnitsCount = publishedUnits!=null?publishedUnits.length:0;
        if (publishedUnitsCount > 0) {

            jQuery("#pw_listing_widget_tabs_detail_avalilable_units_header_tr").empty();
            jQuery("#pw_listing_widget_tabs_detail_avalilable_units_header_tr").append("<th style='text-align:left'>Unit#</th>");
            if (SHOW_FLOOR_PLANS) {
                jQuery("#pw_listing_widget_tabs_detail_avalilable_units_header_tr").append("<th style='text-align:left'>Floor Plan</th>");
            }
            jQuery("#pw_listing_widget_tabs_detail_avalilable_units_header_tr").append("<th style='text-align:center'>Unit Type</th>");
            jQuery("#pw_listing_widget_tabs_detail_avalilable_units_header_tr").append("<th style='text-align:right'>Total Area</th>");
            if (listingWidgetForSaleMode) {
                jQuery("#pw_listing_widget_tabs_detail_avalilable_units_header_tr").append("<th style='text-align:right'>Sale Price</th>");
            } else {
                jQuery("#pw_listing_widget_tabs_detail_avalilable_units_header_tr").append("<th style='text-align:right'>Rent</th>");
                jQuery("#pw_listing_widget_tabs_detail_avalilable_units_header_tr").append("<th style='text-align:right'>Deposit</th>");
            }
            jQuery("#pw_listing_widget_tabs_detail_avalilable_units_header_tbody").empty();
            for (var unitIndex = 0; unitIndex < publishedUnitsCount; unitIndex++) {
                var tr = jQuery(document.createElement("tr"));
                jQuery("#pw_listing_widget_tabs_detail_avalilable_units_header_tbody").append(tr);
                tr.append("<td style=\"text-align:left;\"><a href=\"javascript:loadUnitDetail("+unitIndex+")\"  style='text-decoration:underline'>"+publishedUnits[unitIndex].name+"</a></td>");
                if (SHOW_FLOOR_PLANS) {
                    if (publishedUnits[unitIndex].floorPlan != null) {
                        tr.append("<td style=\"text-align:left;\"><a href=\"javascript:showFloorPlan("+publishedUnits[unitIndex].floorPlan.id+", true)\" style='text-decoration:underline' >"+publishedUnits[unitIndex].floorPlan.name+"</a></td>");
                    } else {
                        tr.append("<td> </td>");
                    }
                }
                tr.append("<td style=\"text-align:center;\">"+publishedUnits[unitIndex].type+"</td>");
                tr.append( "<td style=\"text-align:right;\">"+publishedUnits[unitIndex].totalArea+" "+publishedUnits[unitIndex].areaUnits+" </td>");
                if (listingWidgetForSaleMode) {
                    tr.append("<td style=\"text-align:right;\">"+publishedUnits[unitIndex].salePrice+"</td>");
                } else {
                    tr.append("<td style=\"text-align:right;\">"+publishedUnits[unitIndex].targetRentDescription+"</td>");
                    tr.append("<td style=\"text-align:right;\">"+publishedUnits[unitIndex].targetDeposit+"</td>");
                }
            }
            listingWidgetCurrentBuilding = unit;

            jQuery("#pw_listing_widget_tabs_detail_avalilable_units").show();
        } else {
            jQuery("#pw_listing_widget_tabs_detail_avalilable_units").hide();
        }

        // floor plans
        jQuery("#pw_listing_widget_tabs_detail_floor_plan_detail").empty();


        var floorPlans = unit.floorPlans;
        var floorPlansCount = floorPlans!=null?floorPlans.length:0;
        if (floorPlansCount > 0) {
            jQuery('#tabs-6-link').html("Floor Plans");
            jQuery('#tabs-6-tab').show();
            jQuery("#pw_listing_widget_tabs_detail_floor_plan_select_div").show();
            jQuery("#pw_listing_widget_tabs_detail_floor_plan_select").empty();

            for (var fpIndex = 0; fpIndex < floorPlansCount; fpIndex++) {
                var fpOption = jQuery(document.createElement("option"));
                fpOption.append(floorPlans[fpIndex].name);
                fpOption.attr("value",floorPlans[fpIndex].id);
                jQuery("#pw_listing_widget_tabs_detail_floor_plan_select").append(fpOption);

                var floorPlanMedia = jQuery(document.createElement("div"));
                floorPlanMedia.attr("id", "floorPlanDetail"+floorPlans[fpIndex].id);
                floorPlanMedia.attr("class", "floorPlanDetail");
                if (fpIndex > 0) {
                    floorPlanMedia.hide();
                }
                //floorPlanMedia.append("<h3>" + floorPlans[fpIndex].name + "</h3>");
                floorPlanMedia.append("<span style='font-weight: bold; font-size: 14px'>" + floorPlans[fpIndex].beds + " Bedrooms</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                floorPlanMedia.append("<span style='font-weight: bold; font-size: 14px'>" + floorPlans[fpIndex].baths + " Bathrooms</span> <br /><br />");
                floorPlanMedia.append(floorPlans[fpIndex].embeddedHTMLCode);
                floorPlanMedia.append("<img src=\""+floorPlans[fpIndex].highResUrl+"\" />");
                jQuery("#pw_listing_widget_tabs_detail_floor_plan_detail").append(floorPlanMedia);
            }

        } else if (unit.floorPlan != null) {
            jQuery('#tabs-6-tab').show();
            jQuery('#tabs-6-link').html("Floor Plan");
            jQuery("#pw_listing_widget_tabs_detail_floor_plan_select_div").hide();
            var floorPlanMedia2 = jQuery(document.createElement("div"));
            floorPlanMedia2.append("<br />");
            floorPlanMedia2.append("<h3>" + unit.floorPlan.name + "</h3>");
            floorPlanMedia2.append("<span style='font-weight: bold; font-size: 14px; '>" + unit.floorPlan.beds + " Bedrooms</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
            floorPlanMedia2.append("<span style='font-weight: bold; font-size: 14px'>" + unit.floorPlan.baths + " Bathrooms</span> <br/> <br/>");
            floorPlanMedia2.append(unit.floorPlan.embeddedHTMLCode);
            floorPlanMedia2.append("<img src=\""+unit.floorPlan.highResUrl+"\" />");
            jQuery("#pw_listing_widget_tabs_detail_floor_plan_detail").append(floorPlanMedia2);
        } else {
            jQuery('#tabs-6-tab').hide();
        }
        // amenities
        var unitAmenities = unit.amenities;
        if (unitAmenities.length > 0) {
            var amenitiesUL = jQuery("#pw_listing_widget_tabs_detail_description_amenities_ul").empty();
            for(var i = 0; i < unitAmenities.length; i++){
                amenitiesUL.append("<li>"+unitAmenities[i].name+"</li>");
            }
            jQuery("#pw_listing_widget_tabs_detail_description_amenities").show();
        } else {
            jQuery("#pw_listing_widget_tabs_detail_description_amenities").hide();
        }

        // other info (custom fields)
        var unitCustomFields = unit.customFields;
        if (unitCustomFields.length > 0) {
            var unitCustomFieldsUL = jQuery("#pw_listing_widget_tabs_detail_other_ul").empty();
            for(i = 0; i < unitCustomFields.length; i++){
                unitCustomFieldsUL.append("<li><b>"+unitCustomFields[i].name+": </b>"+unitCustomFields[i].value+"</li>");
            }
            jQuery("#pw_listing_widget_tabs_detail_other").show();
        } else {
            jQuery("#pw_listing_widget_tabs_detail_other").hide();
        }

        // leasing contact
        if (typeof unit.leasingAgent != undefined && unit.leasingAgent != null) {
            jQuery("#pw_listing_widget_tabs_detail_detailLeaseContactName").html(unit.leasingAgent.name);
            jQuery("#pw_listing_widget_tabs_detail_detailLeaseContactCompany").html(unit.leasingAgent.company);
            jQuery("#pw_listing_widget_tabs_detail_detailLeaseContactEmail").html(unit.leasingAgent.email);
            jQuery("#pw_listing_widget_tabs_detail_detailLeaseContactPhone").html(unit.leasingAgent.phone);
            if(unit.leasingAgent.imageID !=""){
                jQuery("#pw_listing_widget_tabs_detail_leasingContactImgTag").attr("src",IMAGE_SERVICE_BASE_URL+unit.leasingAgent.imageID);
            }else{
                jQuery("#pw_listing_widget_tabs_detail_leasingContactImgTag").attr("src",PW_SERVER_URL+"/pw/website/widgets/images/leasingContactPic.png");
            }
            jQuery("#leasingContactDiv").show();
        } else {
            jQuery("#leasingContactDiv").hide();
        }

        //community info
        jQuery("#pw_listing_widget_tabs_detail_detailTools_Schools_Nearby").attr("href", "http://nces.ed.gov/ccd/schoolsearch/school_list.asp?Search=1&amp;InstName=&amp;SchoolID=&amp;Address=&amp;City=&amp;State=&amp;Miles=&amp;County=&amp;PhoneAreaCode=&amp;Phone=&amp;DistrictName=&amp;DistrictID=&amp;SchoolType=1&amp;SchoolType=2&amp;SchoolType=3&amp;SchoolType=4&amp;SpecificSchlTypes=all&amp;IncGrade=-1&amp;LoGrade=-1&amp;HiGrade=-1&amp;Zip="+unit.zip);
        jQuery("#pw_listing_widget_tabs_detail_detailTools_Neighborhood_Profile").attr("href", "http://p01.bestplaces.net/diverse/nhood1.asp?qryZip="+unit.zip);
        jQuery("#pw_listing_widget_tabs_detail_detailTools_Stores_Nearby").attr("href", "http://p01.bestplaces.net/diverse/nearest.asp?qryZip="+unit.zip);
        jQuery("#pw_listing_widget_tabs_detail_detailTools_Restaurants_Nearby").attr("href", "http://www.yelp.com/search?find_desc=&amp;x=41&amp;y=13&amp;cflt=restaurants&amp;find_loc="+unit.zip);

        // tools
        jQuery("#pw_listing_widget_tabs_detail_detailTools_Walkscore").attr("href", "http://www.walkscore.com/get-score.php?go=Go&amp;street="+escape(address + unit.city + ", " + unit.state + " " + unit.zip));
        jQuery("#pw_listing_widget_tabs_detail_detailTools_Homethinking").attr("href", "http://neighborhoods.homethinking.com/");
        jQuery("#pw_listing_widget_tabs_detail_detailTools_CityData").attr("href", "http://www.city-data.com/zips/"+unit.zip+".html");
        var listingLinkUrl = document.location.href;
        if (listingLinkUrl.indexOf('?') >= 0) {
            listingLinkUrl += '&uid='+ unit.id;
        } else {
            listingLinkUrl += '?uid='+ unit.id;
        }
        jQuery("#pw_listing_widget_tabs_detail_detailTools_ListingLink").attr("value", listingLinkUrl);

        if (!unit.rentable) {
            jQuery("#pw_listing_widget_tabs_detail .hideWhenMultiBuilding").hide();
            jQuery("#pw_listing_widget_tabs_detail .showWhenMultiBuilding").show();
        } else {
            jQuery("#pw_listing_widget_tabs_detail .hideWhenMultiBuilding").show();
            jQuery("#pw_listing_widget_tabs_detail .showWhenMultiBuilding").hide();
        }

        var selected = jQuery('#pw_listing_widget_tabs_detail_inner_tabs').tabs('option', 'selected');
        if (selected == 1) {
            loadListingDetailMap();
        }

        jQuery("#pw_listing_widget_tabs_detail_container").fadeIn();
    }
}

function loadListingDetailMap() {
    try {
        jQuery("#pw_listing_widget_tabs_detail_map").empty();
        jQuery("#pw_listing_widget_tabs_detail_streetview").empty();
        var lat = parseFloat(listingWidgetCurrentBuildingOrUnit.latitude);
        var lng = parseFloat(listingWidgetCurrentBuildingOrUnit.longitude);
        var point = new GLatLng(lat, lng);
        var marker = new GMarker(point);

        var panorama = new GStreetviewPanorama(document.getElementById("pw_listing_widget_tabs_detail_streetview"));
        panorama.setLocationAndPOV(point, {yaw: 180, pitch: 0, zoom: 0});
        panorama.checkResize();
        var testPano = new GStreetviewClient();
        testPano.getNearestPanorama(point, function(e) {
            if (e.code == 600 || e.code == 500) {
                jQuery("#pw_listing_widget_tabs_detail_streetview").html("No Street View available for this property.");
            }
        });
        var paddingLeftRight = parseInt(jQuery("#pw_listing_widget_tabs_detail").css("padding-left"), 10) + parseInt(jQuery("#pw_listing_widget_tabs_detail").css("padding-right"), 10);
        var listingWidgetDetailMap = new GMap2(document.getElementById("pw_listing_widget_tabs_detail_map"),{size:new GSize(jQuery("#pw_listing_widget_tabs_detail").width() - paddingLeftRight,350)});
        listingWidgetDetailMap.setUIToDefault();
        listingWidgetDetailMap.addOverlay(marker);
        listingWidgetDetailMap.setCenter(point, 13);
        jQuery("#pw_listing_widget_tabs_detail_map").show();
    } catch(e) {
        alert(e);
    }

}

function gotoDetail(index) {
    if (listingWidgetMapList.length > 0) {
        if (index < 0 && index < listingWidgetMapList.length) {
            index = listingWidgetMapList.length -1;
        } else if (index >= listingWidgetMapList.length) {
            index = 0;
        }
    } else if (listingWidgetListList.length > 0) {
        if (index < 0 && index < listingWidgetListList.length) {
            index = listingWidgetListList.length -1;
        } else if (index >= listingWidgetListList.length) {
            index = 0;
        }
    }
    listingWidgetBuildingIndex = index;
    var selected = jQuery('#pw_listing_widget_tabs').tabs('option', 'selected');
    if (selected == 2) {
        loadDetail();
    } else {
        jQuery("#pw_listing_widget_tabs").tabs('select', 'pw_listing_widget_tabs_detail');

    }
}

function gotoPreviousBuilding() {
    gotoDetail(listingWidgetBuildingIndex -1);
}

function gotoNextBuilding() {
    gotoDetail(listingWidgetBuildingIndex +1);
}

function goBackToBuilding() {
    listingWidgetUnitMode = true;
    listingWidgetUnitIndex = 0;
    loadDetail();
}

function showOnMap(index) {
    if (listingWidgetMapList !== null && listingWidgetMapList.length) {
        // rotation logic
        if (index < 0) {
            index = listingWidgetMapList.length - 1;
        } else if (index > listingWidgetMapList.length -1 ) {
            index = 0;
        }
        listingWidgetBuildingIndex = index;
    } else {
        listingWidgetBuildingIndex = index;
    }
    if (listingWidgetMapList[listingWidgetBuildingIndex] != null) {
        GEvent.trigger(listingWidgetMapList[listingWidgetBuildingIndex].marker, "click");
    }
    jQuery("#pw_listing_widget_tabs").tabs('select', 'pw_listing_widget_tabs_map');
}

function showNextOnMap() {
    showOnMap(listingWidgetBuildingIndex + 1);
    if (listingWidgetMapList[listingWidgetBuildingIndex].marker != null) {
        GEvent.trigger(listingWidgetMapList[listingWidgetBuildingIndex].marker, "click");
    }
}

function showPreviousOnMap() {
    showOnMap(listingWidgetBuildingIndex - 1);
    if (listingWidgetMapList[listingWidgetBuildingIndex].marker != null) {
        GEvent.trigger(listingWidgetMapList[listingWidgetBuildingIndex].marker, "click");
    }
}

function getDirections() {
    jQuery("#pw_listing_widget_tabs_detail_directions_dialog").dialog('open');
}

function submitTenantWaitListForm(){

    var errors = "You must correct the following errors: \n\n";
    var isValid = true;
    var borderStyle = "1px solid #BDB8B8";
    jQuery("#waitListForm input,#waitListForm select").css("border",borderStyle);
    var firstName = document.forms["waitListForm"].elements["webform.contact.contact.firstName"].value;
    firstName = firstName.replace(/^\s+|\s+$/g,"");  //trim
    if (firstName == "") {
        errors += "\n\t* First Name is required";
        isValid = false;
        document.forms["waitListForm"].elements["webform.contact.contact.firstName"].style.border = "2px solid red";
    }

    var lastName = document.forms["waitListForm"].elements["webform.contact.contact.lastName"].value;
    lastName = lastName.replace(/^\s+|\s+$/g,"");  //trim
    if (lastName == "") {
        errors += "\n\t* Last Name is required";
        isValid = false;
        document.forms["waitListForm"].elements["webform.contact.contact.lastName"].style.border = "2px solid red";
    }

    var email =  document.forms["waitListForm"].elements["webform.contact.contact.email"].value;
    var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    if (String(email).search(isEmail_re) == -1) {
        errors += "\n\t* Email is not valid";
        isValid = false;
        document.forms["waitListForm"].elements["webform.contact.contact.email"].style.border = "2px solid red";
    }

    var rentMax =  document.forms["waitListForm"].elements["webform.contact.contact.rentMax"].value;
    rentMax = rentMax.replace(/^\s+|\s+$/g,"");
    if(rentMax != ""){
        if (isNaN(rentMax)) {
            errors += "\n\t* Maximum Monthly Rent field must be a decimal number or blank";
            isValid = false;
            document.forms["waitListForm"].elements["webform.contact.contact.rentMax"].style.border = "2px solid red";
        }
    }


    var rentMin =  document.forms["waitListForm"].elements["webform.contact.contact.rentMin"].value;
    rentMin = rentMin.replace(/^\s+|\s+$/g,"");
    if(rentMin != ""){
        if (isNaN(rentMin)) {
            errors += "\n\t* Minimum Monthly Rent field must be a decimal number or blank";
            isValid = false;
            document.forms["waitListForm"].elements["webform.contact.contact.rentMin"].style.border = "2px solid red";
        }
    }
    var baths =  document.forms["waitListForm"].elements["webform.contact.contact.baths"].value;
    baths = baths.replace(/^\s+|\s+$/g,"");
    if(baths != ""){
        if (isNaN(baths)) {
            errors += "\n\t* Bathrooms field must be a decimal number or blank";
            isValid = false;
            document.forms["waitListForm"].elements["webform.contact.contact.baths"].style.border = "2px solid red";
        }
    }

    var beds =  document.forms["waitListForm"].elements["webform.contact.contact.beds"].value;
    beds = beds.replace(/^\s+|\s+$/g,"");
    if(beds != ""){
        if ((isNaN((beds)) || (parseFloat(beds) != parseInt(beds)))) {
            errors += "\n\t* Bedrooms field must be an integer number or blank";
            isValid = false;
            document.forms["waitListForm"].elements["webform.contact.contact.beds"].style.border = "2px solid red";
        }
    }

    if (!isValid) {
        alert(errors);
    } else {

        var url= RENTAL_SEARCH_WIDGET_BASE_URL+"&action=ctwl"; // ctwl = Create Tenant Wait List
        var pwreferrer = jQuery.cookie('pwreferrer');
        if ( pwreferrer != null) {
            var pwreferrerDecode = encodeURIComponent(pwreferrer);
            url += "&pwreferrer="+ pwreferrerDecode;
        } else {
            url += "&pwreferrer=";
        }
        url += "&pwcampaign=" + (jQuery.cookie("pwcampaign")!=null?jQuery.cookie("pwcampaign"):"");
        url += "&sid=" + SID;
        url += "&firstName=" + document.forms["waitListForm"].elements["webform.contact.contact.firstName"].value;
        url += "&lastName=" + document.forms["waitListForm"].elements["webform.contact.contact.lastName"].value;
        url += "&email=" + document.forms["waitListForm"].elements["webform.contact.contact.email"].value;
        url += "&workPhone=" + document.forms["waitListForm"].elements["webform.contact.contact.workPhone"].value;
        url += "&city=" + document.forms["waitListForm"].elements["webform.contact.contact.city"].value;
        url += "&state=" + document.forms["waitListForm"].elements["webform.contact.contact.state"].value;
        url += "&zip=" + document.forms["waitListForm"].elements["webform.contact.contact.zip"].value;
        url += "&rentMin=" + document.forms["waitListForm"].elements["webform.contact.contact.rentMin"].value;
        url += "&rentMax=" + document.forms["waitListForm"].elements["webform.contact.contact.rentMax"].value;
        url += "&beds=" + document.forms["waitListForm"].elements["webform.contact.contact.beds"].value;
        url += "&baths=" + document.forms["waitListForm"].elements["webform.contact.contact.baths"].value;
        url += "&moveInDate=" + document.forms["waitListForm"].elements["webform.contact.moveInDateAsString"].value;
        url += "&comments=" + document.forms["waitListForm"].elements["webform.contact.comments"].value;
        if (document.forms["waitListForm"].elements["forSalePage"]) {
        url += "&forSalePage=" + document.forms["waitListForm"].elements["forSalePage"].value;
        }



        jsonScript = new JSONscriptRequest(url);
        jsonScript.buildScriptTag();
        jsonScript.addScriptTag();

        jQuery("#pw_listing_widget_wait_list_dialog").dialog('close');
        jQuery("#pw_listing_widget_wait_list_dialog_confirmation").dialog('open');

    }
}

function validateContactAgent() {
    try {
        var errors = "You must correct the following errors: \n\n";
        var isValid = true;
        var firstName = document.forms["guestCardForm"].elements["webform.guest.primaryContact.firstName"].value;
        firstName = firstName.replace(/^\s+|\s+$/g, "");  //trim
        var borderStyle = "1px solid #BDB8B8";
        jQuery("#guestCardForm input,#guestCardForm select").css("border", borderStyle);
        if (firstName == "") {
            errors += "\n\t* First Name is required";
            document.forms["guestCardForm"].elements["webform.guest.primaryContact.firstName"].style.border = "2px solid red";
            isValid = false;
        }
        var lastName = document.forms["guestCardForm"].elements["webform.guest.primaryContact.lastName"].value;
        lastName = lastName.replace(/^\s+|\s+$/g, ""); //trim
        if (lastName == "") {
            errors += "\n\t* Last Name is required";
            document.forms["guestCardForm"].elements["webform.guest.primaryContact.lastName"].style.border = "2px solid red";
            isValid = false;
        }
        var email = document.forms["guestCardForm"].elements["webform.guest.primaryContact.email"].value;
        email = email.replace(/^\s+|\s+$/g, ""); //trim
        if (email == "") {
            errors += "\n\t* Email is required";
            document.forms["guestCardForm"].elements["webform.guest.primaryContact.email"].style.border = "2px solid red";
            isValid = false;
        }
        var workPhone = document.forms["guestCardForm"].elements["webform.guest.primaryContact.workPhone"].value;
        workPhone = workPhone.replace(/^\s+|\s+$/g, ""); //trim
        if (workPhone == "") {
            errors += "\n\t* Day Phone is required";
            document.forms["guestCardForm"].elements["webform.guest.primaryContact.workPhone"].style.border = "2px solid red";
            isValid = false;
        }

        if (!isValid) {
            alert(errors);
        } else {
            var uid = listingWidgetCurrentBuildingOrUnit.id;
            jQuery("#sid").attr("value", SID);
            jQuery("#uid").attr("value", uid!=null?uid:"");
            jQuery("#pwcampaign").attr("value", jQuery.cookie("pwcampaign")!=null?jQuery.cookie("pwcampaign"):"");
            jQuery("#pwreferrer").attr("value", jQuery.cookie("pwreferrer")!=null?jQuery.cookie("pwreferrer"):"");

            var reqParams = jQuery("#guestCardForm").serialize();
            var req;
            if (uid == null) {
                req = SUBMIT_APPLICATION_ACTION + "&action=SubmitForm&callback=handleContactAgentSubmit&forSale=" + listingWidgetForSaleMode + "&" + reqParams;
            } else {
                req = SUBMIT_APPLICATION_ACTION + "&action=SubmitForm&callback=handleContactAgentSubmit&forSale=" + listingWidgetForSaleMode + "&" + reqParams;
            }

            jsonScript = new JSONscriptRequest(req);
            jsonScript.buildScriptTag();
            jsonScript.addScriptTag();
            //        document.contactAgentForm.submit();

            jQuery("#pw_listing_widget_wait_list_dialog_confirmation").dialog('open');
            jQuery("#pw_listing_widget_tabs_detail_inner_tabs").tabs('select', 'tabs-1');

        }
    } catch(e) {
        alert("There was a problem while trying to submit this form: \n" + e);
    }
    return false;
}

function handleContactAgentSubmit(){
    jQuery("#tabs-5").html("Your form has been submitted");
}


function cancelTenantWaitListForm() {
    jQuery("#pw_listing_widget_wait_list_dialog").dialog('close');
}

function showWaitListform(){
    jQuery("#pw_listing_widget_wait_list_dialog").dialog('open');
}

function createElem(opt_className, opt_html, opt_tagName) {
    var tag = opt_tagName||"div";
    var elem = document.createElement(tag);
    if (opt_html) elem.innerHTML = opt_html;
    if (opt_className) elem.className = opt_className;
    return elem;
}

function viewDetailBrochure(){
    var uid = null;
    if (listingWidgetUnitMode && listingWidgetCurrentBuildingOrUnit != null && listingWidgetCurrentBuildingOrUnit.publishedUnits != null && listingWidgetCurrentBuildingOrUnit.publishedUnits[listingWidgetUnitIndex] != null) {
        uid = listingWidgetCurrentBuildingOrUnit.publishedUnits[listingWidgetUnitIndex].id;
    } else if (listingWidgetCurrentBuildingOrUnit != null) {
        uid = listingWidgetCurrentBuildingOrUnit.id;
    }

    if (uid != null) {
        if(listingWidgetForSaleMode) {
            window.open (RENTAL_SEARCH_WIDGET_BASE_URL+"&action="+RENTAL_SEARCH_WIDGET_VIEW_BROCHURE_ACTION+"&uID="+uid+"&sale=true");
        } else {
            window.open (RENTAL_SEARCH_WIDGET_BASE_URL+"&action="+RENTAL_SEARCH_WIDGET_VIEW_BROCHURE_ACTION+"&uID="+uid);
        }
    } else {
        // fallback to listing brochure
        viewListingBrochure();
    }
}

function viewListingBrochure() {
    if(listingWidgetForSaleMode) {
        window.open (RENTAL_SEARCH_WIDGET_BASE_URL+"&action="+RENTAL_SEARCH_WIDGET_VIEW_LISTING_ACTION+"&sale=true&sid="+SID,"Brochure");
    } else {
        window.open (RENTAL_SEARCH_WIDGET_BASE_URL+"&action="+RENTAL_SEARCH_WIDGET_VIEW_LISTING_ACTION+"&sid="+SID,"Brochure");
    }
}

function showContactAgentTab() {
    jQuery('#pw_listing_widget_tabs_detail_inner_tabs').tabs('select', 'tabs-5');
}

function showFloorPlan(id, fromDetail) {

    if (fromDetail) {
        jQuery('#tabs-6-link').click();
        jQuery('#pw_listing_widget_tabs_detail_floor_plan_select').attr("value", id);
    }

    jQuery(".floorPlanDetail").hide();
    jQuery("#floorPlanDetail"+id).show();
}

